<template>
  <div class="relative" @mouseenter="onMouseenter" @mouseleave="onMouseleave">
    <div>
      <!-- 具名插槽：触发弹层的视图 -->
      <slot name="reference" ref="referenceTarget"></slot>
    </div>

    <transition name="slide">
      <div
        v-show="isViable"
        class="absolute p-1 z-20 bg-white dark:bg-zinc-900 border rounded-md dark:border-zinc-700"
        ref="contentTarget"
        :style="contentStyle"
      >
        <!-- 匿名插槽：弹出层视图中展示的内容  -->
        <slot></slot>
      </div>
    </transition>
  </div>
</template>
<script>
//定义气泡出现位置
// 左上
const PROP_TOP_LEFT = 'top-left'

const PROP_TOP_RIGHT = 'top-right'

const PROP_BOTTOM_RIGHT = 'bottom-right'

const PROP_BOTTOM_LEFT = 'bottom-left'

const placementEnum = [
  PROP_TOP_LEFT,
  PROP_TOP_RIGHT,
  PROP_BOTTOM_RIGHT,
  PROP_BOTTOM_LEFT
]
</script>

<script setup>
import { nextTick, ref, watch } from 'vue'

const isViable = ref(false)

const props = defineProps({
  placement: {
    type: String,
    default: PROP_BOTTOM_LEFT,
    validator(val) {
      //查看输入的type是否存在placementEnum中
      const result = placementEnum.includes(val)
      if (!result) {
        throw new Error(
          `你的placement 必须是 ${placementEnum.join('、')}中的一个`
        )
      }
      return result
    }
  }
})

//计算元素的尺寸
const referenceTarget = ref(null)
const contentTarget = ref(null)
const useElementSize = (target) => {
  if (!target) return {}
  return {
    width: target.offsetWidth,
    height: target.offsetHeight
  }
}

//生成气泡样式
const contentStyle = ref({
  top: 0,
  left: 0
})

//气泡展示时进行位置计算
watch(isViable, (val) => {
  if (!val) return
  //vue 在数据发生改变之后，需要等待一段时间DOM才会变化
  nextTick(() => {
    switch (props.placement) {
      case PROP_TOP_LEFT:
        contentStyle.value.top = 0
        contentStyle.value.left =
          -useElementSize(contentTarget.value).width + 'px'
        break
      case PROP_TOP_RIGHT:
        contentStyle.value.top = 0
        contentStyle.value.left =
          useElementSize(referenceTarget.value).width + 'px'
        break
      case PROP_BOTTOM_LEFT:
        contentStyle.value.top =
          useElementSize(referenceTarget.value).height + 'px'
        contentStyle.value.left =
          -useElementSize(contentTarget.value).width + 'px'
        break
      case PROP_BOTTOM_RIGHT:
        contentStyle.value.top =
          useElementSize(referenceTarget.value).height + 'px'
        contentStyle.value.left =
          useElementSize(referenceTarget.value).width + 'px'
        break
    }
  })
})

// 鼠标移入时触发
const onMouseenter = () => {
  isViable.value = true
}

// 鼠标移出时触发
const onMouseleave = () => {
  isViable.value = false
}
</script>

<style scoped>
.slide-enter-active,
.slide-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.slide-enter-from,
.slide-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>
